import React, { useState, useEffect } from 'react';
import { Table, Button, Space, Modal, message, Form, Input, ConfigProvider, Empty } from 'antd';
import type { TableRowSelection } from 'antd/es/table/interface';
import { ExclamationCircleFilled } from '@ant-design/icons';
import { downloadUtils, InbizIcon } from '@inbiz/utils';
import { getMessage, TextWidget } from '@inbiz/react';
import { delSearchLog, delAnalyseLog, editLogSwitch } from '../service';
import { GlobalRegistry } from '@inbiz/core';


// 规定父组件传下来的属性的类型
interface IProps {
    $tableData: any;
    tableData: any;
    tabskey: string;
    getTableData: any;
    searchResult: any;
    $searchResult: any;
    getAnalysisList: any;
    logOpen: boolean;
    $logOpen: any;
    total: any;
    page: any;
    $page: any;
    pageSize: any;
    pagesNum: any;
    loading: any;
}



const BottomTable = (props: IProps) => {
    // 解构
    const { tableData, tabskey, getTableData, searchResult, getAnalysisList, logOpen, $logOpen, page, pageSize, loading } = props

    // 当前勾选行
    const [selectData, $selectData] = useState<any>()

    //  模态框弹窗
    const { confirm } = Modal;

    // 导出弹出框
    const [form] = Form.useForm();

    //   导出弹窗打开关闭状态
    const [isModalOpen, $isModalOpen] = useState(false)

    // 查看详情弹窗开关状态
    const [isDetailOpen, $isDetailOpen] = useState(false)

    // 打开查看详情弹窗
    const showModal = () => {
        $isDetailOpen(true);
    };

    // 当前行的key
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

    // 选中当前行
    const onSelectChange = (newSelectedRowKeys: React.Key[], record: any) => {
        setSelectedRowKeys(newSelectedRowKeys);
        $selectData(record)
    };



    // 点击当前行
    const [columnsData, $columnsData] = useState<any>({})

    // 表头的数据
    const [columns, $columns] = useState<any>([])

    const rowSelection: TableRowSelection<any> = {
        selectedRowKeys,
        onChange: onSelectChange,
        selections: [
            Table.SELECTION_ALL,
            Table.SELECTION_INVERT,
            Table.SELECTION_NONE,
            {
                key: 'odd',
                text: 'Select Odd Row',
                onSelect: (changeableRowKeys) => {
                    let newSelectedRowKeys = [];
                    newSelectedRowKeys = changeableRowKeys.filter((_, index) => {
                        if (index % 2 !== 0) {
                            return false;
                        }
                        return true;
                    });
                    setSelectedRowKeys(newSelectedRowKeys);
                },
            },
            {
                key: 'even',
                text: 'Select Even Row',
                onSelect: (changeableRowKeys) => {
                    let newSelectedRowKeys = [];
                    newSelectedRowKeys = changeableRowKeys.filter((_, index) => {
                        if (index % 2 !== 0) {
                            return true;
                        }
                        return false;
                    });
                    setSelectedRowKeys(newSelectedRowKeys);
                },
            },
        ],
    };



    // 表头数据
    useEffect(() => {
        let columnData: any[] = []
        if (tabskey == 'issueAnalysisLog') {
            columnData = [
                {
                    title: getMessage('LogManagement.type'),
                    dataIndex: 'type',
                    key: 'type',
                    width: 100,
                    ellipsis: true,
                },
                {
                    title: getMessage('LogManagement.url'),
                    dataIndex: 'url',
                    key: 'url',
                    width: '30%',
                    ellipsis: true,

                },
                {
                    title: getMessage('LogManagement.message'),
                    dataIndex: 'message',
                    key: 'message',
                    ellipsis: true,
                    render: (text: any, record: any) => (
                        <div style={{ width: '100%', height: '23px', wordWrap: 'break-word', wordBreak: 'break-word', overflow: 'hidden' }}>{text}</div>
                    )
                },
                {
                    title: getMessage('LogManagement.createTime'),
                    dataIndex: 'createTime',
                    key: 'createTime',
                    width: 180,
                },
                {
                    title: getMessage('LogManagement.operation'),
                    dataIndex: 'operation',
                    key: 'operation',
                    width: 110,
                    render: (td: any, record: any) => (
                        <Space
                            size="middle"
                            align="center"
                            onClick={(e: any) => {
                                e.preventDefault();
                                e.stopPropagation();
                            }}
                        >
                            <a
                                onClick={showModal}
                            >
                                <TextWidget>LogManagement.viewDetail</TextWidget>
                            </a>

                        </Space>
                    ),
                },
            ]
        } else {
            columnData = [
                {
                    title: getMessage('LogManagement.keyWord'),
                    dataIndex: 'keyWord',
                    key: 'keyWord',
                    // width:'20%'
                },
                {
                    title: getMessage('LogManagement.indexName'),
                    dataIndex: 'indexName',
                    key: 'indexName',
                    width: '20%'
                },
                {
                    title: getMessage('LogManagement.searchPeople'), //'搜索人'
                    dataIndex: 'userName',
                    key: 'userName',
                    width: '20%'
                },
                {
                    title: getMessage('LogManagement.searchTime'), //发起时间
                    dataIndex: 'createTime',
                    key: 'createTime',
                    width: 180,
                }
            ]
        }
        $columns(columnData)

    }, [tabskey, GlobalRegistry.getDesignerLanguage()])


    // 确认删除的弹窗
    const handledelete = (selectedRowKeys: any) => {
        confirm({
            title: getMessage('LogManagement.confirmDel'),
            icon: <ExclamationCircleFilled />,
            content: getMessage('LogManagement.noRevert'),
            className:'inbiz-log-management-component-Modal',
            centered:true,
            bodyStyle:{height:'164px'},
            okText: getMessage('LogManagement.confirm'),
            cancelText: getMessage('LogManagement.cancel'),
            onOk() {
                let ids = selectedRowKeys?.join(',')
                DelList(ids);
            },
            onCancel() { },
        });
    };

    //删除方法
    const DelList = (ids: string) => {

        if (tabskey == 'issueAnalysisLog') {
            // 删除问题分析日志
            delAnalyseLog(ids).then((res: any) => {
                if (res?.Code == '0') {
                    message.success(getMessage('LogManagement.deleteSucess'))
                    setSelectedRowKeys([])
                    getAnalysisList(page, pageSize, searchResult);
                } else {
                    message.error(getMessage('LogManagement.deleteFail'))
                }
            });

        } else {
            // 删除搜索日志
            delSearchLog(ids).then((res: any) => {
                if (res?.Code == '0') {
                    message.success(getMessage('LogManagement.deleteSucess'))
                    setSelectedRowKeys([])
                    getTableData(page, pageSize, searchResult)
                } else {
                    message.error(getMessage('LogManagement.deleteFail'))
                }
            });
        }

    };

    // 确定导出
    const handleOk = () => {
        let ids: any[] = []
        // 指定项下载
        if (selectedRowKeys?.length) {
            selectData?.map((item: any) => {
                ids.push(item.id)
            })
        }
        let fileNames=getMessage('LogManagement.searchLog')
        form.validateFields().then((res)=>{
            fileNames=res.name
            let url = `/search/IndexSystem/ExportSearchKeyWordLogList?KeyWord=${searchResult?.KeyWord || (searchResult ? '' : '*')}&ids=${ids.join(',') || (searchResult ? '' : '*')}&StartTime=${searchResult?.StartTime || ''}&EndTime=${searchResult?.EndTime || ''}&IndexId=${searchResult?.IndexId || ''}&UserName=${searchResult?.UserName || ''}&FileName=${fileNames}`
            downloadUtils.downloadFile(url, (iframeDoc?: any) => {
                if (iframeDoc?.URL == "about:blank" && iframeDoc?.referrer == '') {
                    message.success(getMessage('LogManagement.exportSuccess'))
                } else if (iframeDoc?.URL != "about:blank" || (iframeDoc?.referrer != '')) {
                    message.error(getMessage('LogManagement.exportFail'))
                }
            })
        })


        $isModalOpen(false)
    }
    // 取消导出
    const handleCancel = () => {
        $isModalOpen(false)
    }

    return (
        <>
            <div className="bottomTable">
                <div className="buttons">
                    <Space size="middle">
                        <Button disabled={selectedRowKeys.length ? false : true}
                            onClick={() => {
                                handledelete(selectedRowKeys);
                            }}>
                            <InbizIcon type="icon-ic-tree-huishouzhan" />
                            <span><TextWidget>LogManagement.delete</TextWidget></span>
                        </Button>
                        {tabskey == 'issueAnalysisLog' ? <Button onClick={() => {
                            editLogSwitch(!logOpen)
                            logOpen ? $logOpen(false) : $logOpen(true)
                        }}>
                            {logOpen? getMessage('LogManagement.close') : getMessage('LogManagement.open')}
                        </Button> :
                            <Button onClick={() => {
                                $isModalOpen(true)
                            }}>
                                <InbizIcon type="icon-daochu" />
                                <span><TextWidget>LogManagement.export</TextWidget></span>
                            </Button>
                        }


                    </Space>
                </div>
                <Table
                    onRow={record => {
                        return {
                            onMouseEnter: event => {
                                $columnsData(record)
                            }
                        }
                    }}
                    loading={loading}
                    rowSelection={rowSelection}
                    columns={columns}
                    dataSource={tableData}
                    bordered={true}
                    pagination={false}
                    locale={{
                        emptyText: (
                            <Empty
                                image={loading ? null : Empty.PRESENTED_IMAGE_SIMPLE}
                                description={
                                    loading ? null : (
                                        <TextWidget>LogManagement.noData</TextWidget>
                                    )
                                }
                            />
                        ),
                    }}
                />

            </div>
            {/* 导出弹窗 */}
            <Modal
                title={getMessage('LogManagement.export')}
                visible={isModalOpen}
                onOk={handleOk}
                onCancel={handleCancel}
                width={440}
                style={{ fontSize: '12px' }}
                bodyStyle={{ height: '114px', paddingTop: '40px', boxSizing: 'border-box' }}
                centered={true}
                okText={getMessage('LogManagement.confirm')}
                cancelText={getMessage('LogManagement.cancel')}
                forceRender
            >
                <Form
                    form={form} colon={false}
                    initialValues={{name: getMessage('LogManagement.searchLog')}}
                    preserve={false}
                >
                    <Form.Item
                        name="name"
                        label={<TextWidget>LogManagement.fileName</TextWidget>}
                        rules={[{ required: true,message:getMessage('LogManagement.pleaseInput')+getMessage('LogManagement.fileName') }]}
                    >
                        <Input
                                style={{
                                    width:'304px',
                                    borderColor: 'rgb(214, 214, 214)',
                                    padding: '2px 2px 2px 10px',
                                    margin: '0px 6px 0px 10px'
                                }}
                            />
                    </Form.Item>
                </Form>
            </Modal>
            {/* 查看详情弹窗 */}
            {
                <>
                    <Modal forceRender title={getMessage('LogManagement.logDetail')} width={600} bodyStyle={{ maxHeight: '540px', paddingBottom: '10px', overflow: 'auto' }} visible={isDetailOpen} onCancel={() => $isDetailOpen(false)} closeOnMaskClick={true} footer={null} >

                        {columnsData?.detail}

                    </Modal>
                </>
            }
        </>
    )
}

export default BottomTable;
